<?php
/**
 * User zgh
 * Email 1803897171@qq.com
 * Date 2021/9/4
 **/

namespace app\api\controller;


use app\common\util\RedisUtil;
use think\facade\Request;

class TaskController
{

    /**
     * 发布订阅
     */
    public function publish()
    {

        if (Request::isAjax()) {
            $user_id = (int)Request::param("user_id", 0);
            $good_id = (int)Request::param("good_id", 0);
            if (!$user_id || !$good_id) {
                return json_response("用户ID或商品Id参数错误");
            }
            /**
             * @var $redis \Redis
             */
            $redisUtil= new RedisUtil(); $redis = $redisUtil->getHandler();
            // 使用布隆过滤器 检验 good_id的合法性
            $lua = <<<LUA_SCRIPY
            local ret = redis.call("BF.EXISTS",KEYS[1],ARGV[1]);
            return ret;
LUA_SCRIPY;
            $good_exist = $redis->eval($lua, [RedisUtil::getPrefix() . "goods", "good_" . $good_id], 1);
            if (!$good_exist) {
                return json_response("没找到相关的抢购商品");
            }
            $queue_status = $redis->hGet(RedisUtil::getPrefix() . "goods:" . $good_id, "userid_" . $user_id);
            if ($queue_status == 1) {
                return json_response("正在抢购队列中,请不要频繁提交!");
            } elseif ($queue_status == 2) {
                return json_response("商品已经抢购过,不能重复购买");
            }
            //发布消息到频道
            $publish = $redis->publish("order", serialize(["user_id" => $user_id, "good_id" => $good_id]));
            if (!$publish) {
                return json_response("抢购失败,请稍后重试!");
            }
            //进入排队队列
            $redis->hSet(RedisUtil::getPrefix() . "goods:" . $good_id, "userid_" . $user_id, 1);
            return success_json_response("正在抢购中,请耐心等待");
        }
    }


}